(function(window,document) {
    "use strict";
    var MobileQuery = function (selector) {
    };
    var byId=document.getElementById.bind(document);
    MobileQuery.fn = {};
    MobileQuery.fn.Init = function (selector) {
    };
    MobileQuery.setStorage = function (key, obj) {
        if (MobileQuery.isNull(obj)) {
            window.localStorage.setItem(key, JSON.stringify(obj));
        }
    };
    MobileQuery.getStorage = function (key) {
        var objstring = window.localStorage.getItem(key);
        if (MobileQuery.isNull(key)) {
            return JSON.parse(objstring);
        }
        return '';
    };
    MobileQuery.isNull = function (key) {
        if(typeof key == "string") key=this.trim(key);
        if(key && key != 'undefined' && key != null && key != '' && key != 'null') {
            return true;
        }
        return false;
    };
    MobileQuery.clearStorage = function (key) {
        window.localStorage.removeItem(key);
    };
    MobileQuery.openWin = function (o) {
        var op={
            createNew: false,
            waiting:{
                autoShow:false
            },
            show:{
                autoShow:true,//页面loaded事件发生后自动显示，默认为true
                aniShow:'slide-in-right',//页面显示动画，默认为”slide-in-right“；
                event:'titleUpdate',//页面显示时机，默认为titleUpdate事件时显示
                extras:{}//窗口动画是否使用图片加速
            },
            styles: {
                top: 0, //新页面顶部位置
                bottom: 0 //新页面底部位置
            }
        };
        op = mui.extend(true,op,o);
        mui.openWindow(op);
    };
    MobileQuery.pathJoin = function (path1, path2) {
        return path1 + path2;
    };
    MobileQuery.ajax = function (o) {
        //判断网络状态
        if(!$$.isNetwork) {
            $$.toast("无网络");
            return;
        }
        var _op={
            url:"",
            data:{},
            dataType:'json',//服务器返回json格式数据
            type:'post',//HTTP请求类型
            crossDomain:true,
            timeout:10000,//超时时间设置为10秒；
            success:function(data){},
            error:function(xhr,type,errorThrown){}
        };
        _op = mui.extend(true,_op,o);
        console.log(JSON.stringify(_op.data))
        mui.ajax(_op.url, _op);
    };
    MobileQuery.upload = function (o){
        //判断网络状态
        if(!$$.isNetwork) {
            $$.toast("无网络");
            return;
        }
        var task = plus.uploader.createUpload(o.url,
            { method:"POST",blocksize:2048000,priority:0 },
            function ( t, status ) {
                // 上传完成
                if ( status == 200 ) {
                    o.success(t.responseText&&JSON.parse(t.responseText));
                } else {
                    o.error(t);
                }
            }
        );
        if(o.data.img){
            /*for(var k=0;k< o.data.img.length;k++){
                task.addFile(o.data.img[k],{key:"img"});
            }*/
            task.addFile(o.data.img,{key:"img"});
        }
        //
        if(o.data.file) {
            task.addFile(o.data.file, {key: "file"});
        }
        if(o.data.files&&o.data.files instanceof Array){
            for(var f=0;f< o.data.files.length;f++){
                var fs = o.data.files[f];//
                task.addFile(fs,{key:"file"+(f+1)});
            }
        }
        if(o.data.imgs&&o.data.imgs instanceof Array){
            for(var i=0;i< o.data.imgs.length;i++){
                var fsImg = o.data.imgs[i];//
                task.addFile(fsImg,{key:"img"+(i+1)});
            }
        }
        for(var ke in o.data){
            if(ke!="file"&&ke!="img"&&ke!="files"&&ke!="imgs"){
                task.addData(ke, o.data[ke]);
            }
        }
        task.start();
    };
    MobileQuery.down =function(o){
        //判断网络状态
        if(!$$.isNetwork) {
            $$.toast("无网络");
            return;
        }
        var _op={
            url:"",
            filename:"",
            success:function(){}
        };
        _op =mui.extend(false,_op,o);
        var _dtask = plus.downloader.createDownload(_op.url,
            {
            filename:'_doc/'+ _op.filename
            },
            function ( d, status ) {
                // 下载完成
                if ( status == 200 ) {
                    try {
                        _op.success(d.responseText && JSON.parse(d.responseText));
                    }catch(e){
                        _op.success();
                    }
                } else {
                    o.error();
                }
        });
        _dtask.start();
    };
    MobileQuery.closeStack = function () {
        mui.plusReady(function () {
            var wvs = plus.webview.all();
            if (wvs.length > 10) {
                plus.webview.close(wvs[0].id);
            }
        });
    };
    MobileQuery.toast = function (title, o) {
        mui.toast(title, {
            duration: o||'long',
            type: 'div'
        });
    };
    MobileQuery.confirm = function(title,callback){
        mui.confirm(title,"确认",["是","否"],callback);
    };
    MobileQuery.render = function (o) {
        var _op={
            viewId:"view",
            tempId:"template",
            data:{},
            callback:function(){}
        };
        _op=mui.extend(false,_op,o);
        var _template = byId(_op.tempId).innerHTML;
        laytpl(_template).render(_op.data, function (html) {
            byId(_op.viewId).innerHTML = html;
            var _script=document.createElement('script');
            _script.type="text/html";
            _script.id= _op.tempId;
            _script.innerHTML=template;
            byId(_op.viewId).appendChild(_script);
            _op.callback();
        });
    };
    MobileQuery.showLoading=function(){
        //创建Loading
        var _loading = document.createElement('div');
        _loading.className="boxs";
        _loading.id="load-box";
        var _dom="";
        _dom+='<div class="spinner">';
        _dom+='<div class="spinner-container container1">';
        _dom+='<div class="circle1"></div>';
        _dom+='<div class="circle2"></div>';
        _dom+='<div class="circle3"></div>';
        _dom+='<div class="circle4"></div>';
        _dom+='</div>';
        _dom+=' <div class="spinner-container container2">';
        _dom+='<div class="circle1"></div>';
        _dom+='<div class="circle2"></div>';
        _dom+='<div class="circle3"></div>';
        _dom+='<div class="circle4"></div>';
        _dom+='</div>';
        _dom+=' <div class="spinner-container container3">';
        _dom+='<div class="circle1"></div>';
        _dom+='<div class="circle2"></div>';
        _dom+='<div class="circle3"></div>';
        _dom+='<div class="circle4"></div>';
        _dom+='</div>';
        _dom+='</div>';
        _loading.innerHTML=_dom;
        _loading.style.display="block";
        document.getElementsByTagName('body')[0].appendChild(_loading);
    };
    MobileQuery.closeLoading=function(){
        var _load=byId('load-box');
        if(_load){
            _load.parentNode.removeChild(_load);
            _load=null;
        }
    };
    MobileQuery.webCurr=function(){
        return plus.webview.currentWebview();
    };
    MobileQuery.webById=function(id){
        return plus.webview.getWebviewById(id);
    };
    MobileQuery.initBtn=function(){
        //Material Design Button
        mui('body').on('touchstart','.md-design',function(e){
            var x = e.touches[0].clientX ,
                y = e.touches[0].clientY,
                left=this.offsetLeft,
                top=this.offsetTop;
            var divDOM=document.createElement('div');
            divDOM.className="md-ripple md-ripple-effect";
            divDOM.style.left=(x-left-7)+'px';
            divDOM.style.top=(y-top-5)+'px';
            this.appendChild(divDOM);
            var _this=this;
            setTimeout(function(){
                _this.removeChild(divDOM);
            },2000);
        });
    };
    MobileQuery.IO={
        createDr:function(o){
            var _files={
                path: '/_doc/',//当前目录
                dr:[],//保存目录对象
                fs:[]//保存文件对象
            };
            plus.io.resolveLocalFileSystemURL((o.path),function(entry){
                _files.path= o.path;
                //创建目录读取对象
                var readerDr = entry.createReader();
                //读取目录 返回文件对象和目录对象数组
                readerDr.readEntries(function (e2) {
                    for (var i = 0; i < e2.length; i++) {
                        var file = e2[i];
                        //判断是文件还是目录对象
                        if (file.isFile) {
                            //文件
                            _files.fs.push(file);
                        } else {
                            //目录
                            _files.dr.push(file);
                        }
                    }
                    o.success(_files);
                }, function (ev) {
                    o.error(ev);
                });
            });
        }
    };
    MobileQuery.trim=function(str){
       return str.replace(/(^\s*)|(\s*$)/g, "");
    };
    MobileQuery.isNetwork=function(){
        //判断是否有网络
       return plus.networkinfo.getCurrentType()==0;
    };
    MobileQuery.initScroll=function(op){
        var options = {
            scrollY: true, //是否竖向滚动
            scrollX: false, //是否横向滚动
            startX: 0, //初始化时滚动至x
            startY: 0, //初始化时滚动至y
            indicators: false, //是否显示滚动条
            deceleration:0.0006, //阻尼系数,系数越小滑动越灵敏
            bounce: true //是否启用回弹
        };
        options = mui.extend(true,options,op);
        mui('.mui-scroll-wrapper').scroll(options);
    };
    MobileQuery.initSheet=function(op){
        var _op={
          el:"#add-sheet",
          callback:function(){}
        };
        _op=mui.extend(true,_op,op);
        var  _sheet =mui(_op.el);
        var _sheetDOM=_sheet[0];
        var _action={
            show:function(){
                _sheetDOM.classList.add('item-sheet-show');
            },
            hide:function(){
                _sheetDOM.classList.remove('item-sheet-show');
            }
        };
        _sheet.on('tap','.item-sheet',function(){
            var _index=this.getAttribute('data-index');
            var _flag=_op.callback(this,+_index);
            if(_flag){
                _action.hide();
            }
        });
        document.getElementsByTagName('body')[0].addEventListener('tap',function(e){
            if(!e.target.classList.contains('item-sheet')&&!e.target.classList.contains('add-sheet')&&!e.target.classList.contains('mui-pull-right')){
                _action.hide();
            }
        });
        return _action;
    };
    MobileQuery.initCheckBox=function(op){
        //需要特定css release.css
        if(!layer){return console.log("layer undefined")}
        var _op={
            title:"标题",
            data:[{
                text:"列表1",
                value:0
            }],
            reset:function(){},
            click:function(){},
            success:function(){}
        };
        _op=mui.extend(true,_op,op);
        var content="";
        content+="<div class='welfareBox'>";
        content+="<span>"+_op.title+"</span>";
        content+='<div class="mui-scroll-wrapper" style="top: 1rem;bottom: 1rem;left: 0.55rem;right: 0.3rem;width: auto">';
        content+='<div class="mui-scroll">';
        mui.each(_op.data,function(index,item){
            content+='<div class="mui-input-row mui-checkbox">';
            content+='<label>'+item.text+'</label>';
            content+='<input name="checkbox1" class="l-check" data-value="'+item.value+'" data-text="'+item.text+'" type="checkbox">';
            content+='</div>';
        });
        content+="</div>";
        content+="</div>";
        content+='<div class="btns-box"><span onclick="CheckBoxResetClick(this)">重置</span><span onclick="CheckBoxOkClick(this)">确定</span></div>';
        content+="</div>";
       var _index= layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            content: content,
            success:function(){
                $$.initScroll();
                _op.success();
            },
            end:function(){
                //销毁
                window.CheckBoxResetClick=null;
                window.CheckBoxOkClick=null;
            }
        });
        window.CheckBoxResetClick=function(dom){
            var checks=document.getElementsByClassName('l-check');
            if(!checks){checks=[];}
            mui.each(checks,function(index,item){
                if(item.checked===true) {
                    item.checked=false;
                }
            });
            _op.reset();
        };
        window.CheckBoxOkClick=function(dom){
            var cheArr=[];
            var checks=document.getElementsByClassName('l-check');
            if(!checks){checks=[];}
            mui.each(checks,function(index,item){
                if(item.checked===true) {
                    var val = item.getAttribute('data-value');
                    var text = item.getAttribute('data-text');
                    cheArr.push({
                        text: text,
                        value: val
                    })
                }
            });
            _op.click(cheArr);
            layer.close(_index);
        };
    };
    window.$$=MobileQuery;
})(window,document);